<?php

/**
 * 渝欧供应商JDK
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopyuouApi;
use App\Service\Code\Normal;
use App\Service\BaseService;
use Service\AppService\IdService;
use App\Service\TaskServer\TaskWorker;
use function EasySwoole\Spl\trim;

class ShopyuouApiClient extends BaseService
{    
    private $config = [];
    public function __construct() 
    {
        $this->config = config("api.shopyuou");
    }
    
    /**
     * 创建订单
     * @param array $params
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        $orderInfo          = $param['supplierOrder'];
        $goodsList          = $param['orderGoods'];
        $order              = $param['order'];
        $binfo              = $param['binfo'];
        
        //运费分摊
        $deliver_money = $orderInfo['deliver_money'];
        //获取下单商品信息
        $palceOrderGoods = [];
        foreach ($goodsList as $key => $item )
        {
            //卖价
            $price          = $item['price'];
            //商品购买规格数量
            $spec_num       = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity       = $item['quantity'];
            //实际购买数量
            $buyAcount      = $spec_num * $quantity ;
            
            //计算商品税前商品总金额公式应为：
            //custom_price  * qty + shipping_fee - discount
            
            //假设商品的综合税率为 r，那么商品的实际支付(报关)金额应为：
            //（custom_price  * qty + shipping_fee - discount）* r + custom_price  * qty + shipping_fee - discount - bonus_money
            
            //商品税率
            $tax                        = $item['tax_rate'];
            $tax_rate                   = bcadd((string)$tax,'1.0000',4);
            
            //商品+税费
            $shipping_fee               = $key == 0 ? $deliver_money : 0;
            $single_shipping_fee        = bcdiv((string)$shipping_fee,(string)$quantity,3);
            $single_shipping_fee        = ceil((float)$single_shipping_fee * 100)/100;
            $price                      = bcadd((string)$price, (string)$single_shipping_fee,2);
            //包邮价格
            $goodsMoney                 = bcmul((string)$price, (string)$quantity,2);
            
            //获取商品不含税价格 ,小数第三位收了之后再进行合计计算
            $goods_price                = bcdiv((string)$goodsMoney, (string)$tax_rate,3);
            $goods_price                = bcdiv((string)$goods_price, (string)$buyAcount,3);
            $singleGoodsPrice           = ceil((float)$goods_price * 100)/100;
            $singleGoodsSummaryMoney    = bcmul((string)$singleGoodsPrice, (string)$buyAcount,2);
            
            //税金
            $SummaryTaxAmt              = bcsub((string)$goodsMoney, (string)$singleGoodsSummaryMoney,2);
            $SummaryGoodsMoney          = bcadd((string)$SummaryTaxAmt, (string)$singleGoodsSummaryMoney,2); 
            //金额差异 放在优惠金额
            $sub_goods_money            = bcsub((string)$goodsMoney, (string)$SummaryGoodsMoney,2);
            
            //下单商品组
            $palceOrderGoods[] = [
                'goods_sn'          => \trim($item['supplier_skucode']),
                'custom_price'      => $singleGoodsPrice,
                'qty'               => $buyAcount,
                'shipping_fee'      => 0.00,
                'added_value_tax'   => $SummaryTaxAmt,
                'activity_discount' => $sub_goods_money,
                'bonus_money'       => 0.00,
            ];
        }
        
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //组装推送上游数据
        $requestParam = [
            'consignee'             => $orderInfo['receive_name'],
            'id_card_no'            => $orderInfo['buyer_idcard'],
            'mobile'                => $orderInfo['recveive_phone'],
            'province_name'         => $orderInfo['province'],
            'city_name'             => $orderInfo['city'],
            'district_name'         => $orderInfo['district'],
            'address'               => $orderInfo['receive_address'],
            'remark'                => $orderInfo['order_remark'],
            'order_third_party_no'  => $orderInfo['supplier_dsn'],
            'ebp_code'              => $order['enterpriseNum']??$apply_extends['enterpriseNum']??'',
            'ebp_name'              => $order['enterpriseName']??$apply_extends['enterpriseName']??'',
            'goods_list'            => json_encode($palceOrderGoods,JSON_UNESCAPED_UNICODE),
        ];
        $data = [
            'method' => 'createOrder',
            'data' => $requestParam,
        ];
        return $this->execute($data);
    }
    
    //验签
    public function sign( $param=array() )
    {
        ksort($param);
        $arr = [];
        foreach ($param as $k=>$v){
            $arr[] = "{$k}={$v}";
        }
        
        $str = implode("&", $arr).$this->config['SECRET_KEY'];
        $str = md5($str);
        return $str;
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        $url = $this->config['API_DOMAIN'].$this->config['acount'][$param['method']];
        if( empty($url) ) {
            return Normal::returnCode(Normal::FAIL,"接口地址不能为空");
        }
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        
        $data = $param['data'];
        $pushData = array_merge($data,[
            'timestamp' => date('Y-m-d H:i:s'),
            'app_key'   => $this->config['APP_KEY'],
        ]);
        
        $pushData['sign'] = $this->sign($pushData);
        $parameter = [
            [
                'tag'       => 'shopyuou_'.$param['method'],
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $pushData,
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $result  = @json_decode($resTask['response']['result'],true);
        if( isset($result['code']) && $result['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"OK",[
                'thirdpart_order_sn' => $result['data']['order_sn']
            ]);
        } else {
            $msg = isset($result['message']) ? $result['message'] : '请求失败' ;
            return Normal::returnCode(Normal::FAIL,$msg);
        }
    }
}